<template>
  <div class="adminer-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>管理员管理</span>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-4">
        <el-form-item label="姓名">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入姓名"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="学工号">
          <el-input
            v-model="queryForm.henau_number"
            placeholder="请输入学工号"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-input
            v-model="queryForm.section"
            placeholder="请输入部门"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryForm.phone"
            placeholder="请输入手机号"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="身份状态">
          <el-select
            v-model="queryForm.identity_status"
            placeholder="请选择身份状态"
            clearable
            class="!w-[180px]"
          >
            <el-option label="本科生" :value="0" />
            <el-option label="研究生" :value="1" />
            <el-option label="在校教职工" :value="2" />
            <el-option label="在校后勤/外聘人员" :value="3" />
            <el-option label="已毕业校友" :value="4" />
            <el-option label="中国现代农业联合研究生院学生" :value="5" />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区 -->
      <div class="flex justify-between mb-4">
        <div class="flex gap-2">
          <el-button type="primary" @click="handleQuery">
            <el-icon class="mr-2"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetForm">
            <el-icon class="mr-2"><Refresh /></el-icon>重置
          </el-button>
        </div>
        <div class="flex gap-2">
          <el-button type="primary" @click="handleAddAdmin">
            <el-icon class="mr-2"><Plus /></el-icon>新增管理员
          </el-button>
          <el-button type="success" @click="handleDownloadTemplate">
            <el-icon class="mr-2"><Download /></el-icon>下载模板
          </el-button>
          <el-button type="warning" @click="handleImport">
            <el-icon class="mr-2"><Upload /></el-icon>导入管理员
          </el-button>
        </div>
      </div>

      <!-- 管理员列表 -->
      <PureTable
        row-key="id"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        border
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      >
        <template #avatar="{ row }">
          <el-avatar :size="40" :src="row.avatar_url" />
        </template>
        <template #ip="{ row }">
          <div class="flex flex-wrap gap-1 justify-center">
            <template v-if="row.allow_ip">
              <el-tag
                v-for="ip in JSON.parse(row.allow_ip)"
                :key="ip"
                :type="getIpTagType(ip)"
                effect="light"
                size="small"
                class="ip-tag"
              >
                {{ ip }}
              </el-tag>
            </template>
            <el-tag v-else type="info" effect="light" size="small"
              >未设置</el-tag
            >
          </div>
        </template>
        <template #status="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
        <template #role="{ row }">
          <div class="flex flex-wrap gap-1 justify-center">
            <el-tag
              v-for="role in sortRolesByAdminId(row.role_names, row.role_id)"
              :key="role"
              :type="getTagType(role.trim())"
              effect="light"
              size="small"
              class="role-tag"
            >
              <el-icon class="mr-1"><UserFilled /></el-icon>
              {{ role.trim() }}
            </el-tag>
          </div>
        </template>
      </PureTable>
    </el-card>

    <!-- 新增管理员对话框 -->
    <el-dialog
      v-model="addAdminDialogVisible"
      title="新增管理员"
      width="500px"
      :destroy-on-close="true"
    >
      <el-form
        ref="addAdminFormRef"
        :model="addAdminForm"
        :rules="addAdminRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="学工号" prop="number">
          <el-input v-model="addAdminForm.number" placeholder="请输入学工号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addAdminForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="允许IP" prop="allow_ip">
          <el-input
            v-model="addAdminForm.allow_ip"
            placeholder="请输入允许的IP地址"
          />
        </el-form-item>
        <el-form-item label="默认角色" prop="default_roles">
          <el-select
            v-model="addAdminForm.default_roles"
            placeholder="请选择默认角色"
            multiple
            clearable
            filterable
            :filter-method="filterRoles"
            @visible-change="handleRoleSelectVisible"
          >
            <el-option
              v-for="role in filteredRoleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            >
              <span>{{ role.name }}</span>
              <span class="text-gray-400 text-xs ml-2">{{
                role.description
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAdminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddAdminSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑角色" width="500px">
      <el-form
        ref="formRef"
        :model="adminForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="adminForm.name"
            disabled
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="学工号" prop="henau_number">
          <el-input
            v-model="adminForm.henau_number"
            disabled
            placeholder="请输入学工号"
          />
        </el-form-item>
        <el-form-item label="部门" prop="section">
          <el-input
            v-model="adminForm.section"
            disabled
            placeholder="请输入部门"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="adminForm.phone"
            disabled
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="身份状态" prop="identity_status">
          <el-select
            v-model="adminForm.identity_status"
            placeholder="请选择身份状态"
            disabled
          >
            <el-option label="本科生" :value="0" />
            <el-option label="研究生" :value="1" />
            <el-option label="在校教职工" :value="2" />
            <el-option label="在校后勤/外聘人员" :value="3" />
            <el-option label="已毕业校友" :value="4" />
            <el-option label="中国现代农业联合研究生院学生" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色信息" prop="role_id">
          <el-select
            v-model="adminForm.role_id"
            placeholder="请选择角色"
            multiple
            clearable
            filterable
            :filter-method="filterRoles"
            @visible-change="handleRoleSelectVisible"
          >
            <el-option
              v-for="role in filteredRoleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            >
              <span>{{ role.name }}</span>
              <span class="text-gray-400 text-xs ml-2">{{
                role.description
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入管理员弹窗 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入管理员"
      width="500px"
      :destroy-on-close="true"
    >
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :show-file-list="true"
        :on-change="handleFileUpload"
        :before-upload="
          file => {
            const isExcel = ['xlsx', 'xls'].includes(
              file.name.split('.').pop().toLowerCase()
            );
            if (!isExcel) {
              ElMessage.error('只能上传 Excel 文件（.xlsx 或 .xls 格式）');
            }
            return isExcel;
          }
        "
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            只能上传 Excel 文件（.xlsx 或 .xls 格式），且文件大小不能超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { ElMessage, ElMessageBox, ElButton, ElIcon, ElTag } from "element-plus";
import type { FormInstance } from "element-plus";
import {
  Search,
  Refresh,
  UserFilled,
  Download,
  Upload,
  UploadFilled,
  Edit,
  Plus
} from "@element-plus/icons-vue";
import {
  getAdminerList,
  getAllRoles,
  setAdminerRole,
  setAdminerStatus,
  preAllow,
  setAllow
} from "@/api/index";
import PureTable from "@pureadmin/table";
import * as XLSX from "xlsx";

interface AdminUser {
  id: number;
  name: string;
  avatar_url: string;
  henau_number: string;
  section: string;
  phone: string;
  identity_status: number;
  role_names: string;
  role_id: number[];
  status: number;
  allow_ip: string;
}

const loading = ref(false);
const dataList = ref<AdminUser[]>([]);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const importDialogVisible = ref(false);
const addAdminDialogVisible = ref(false);
const addAdminFormRef = ref<FormInstance>();

// 分页配置
const pagination = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

// 查询表单数据
const queryForm = reactive({
  page: 1,
  size: 10,
  name: "",
  henau_number: "",
  section: "",
  phone: "",
  status_id: "",
  identity_status: ""
});

// 表单数据
const adminForm = ref<AdminUser>({
  id: 0,
  name: "",
  avatar_url: "",
  henau_number: "",
  section: "",
  phone: "",
  identity_status: 0,
  role_names: "",
  role_id: [],
  status: 1,
  allow_ip: ""
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  henau_number: [{ required: true, message: "请输入学工号", trigger: "blur" }],
  section: [],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  identity_status: []
};

// 定义表格列
const columns = [
  {
    label: "ID",
    prop: "id",
    sortable: true,
    width: 80,
    align: "center"
  },
  {
    label: "头像",
    prop: "avatar_url",
    width: 80,
    slot: "avatar",
    align: "center"
  },
  {
    label: "姓名",
    prop: "name",
    minWidth: 100,
    align: "center"
  },
  {
    label: "学工号",
    prop: "henau_number",
    minWidth: 120,
    align: "center"
  },
  {
    label: "部门",
    prop: "section",
    minWidth: 120,
    align: "center"
  },
  {
    label: "手机号",
    prop: "phone",
    width: 120,
    align: "center"
  },
  {
    label: "身份状态",
    prop: "identity_status",
    width: 120,
    align: "center",
    formatter: (row: AdminUser) => {
      const statusMap = {
        0: "本科生",
        1: "研究生",
        2: "在校教职工",
        3: "在校后勤/外聘人员",
        4: "已毕业校友",
        5: "中国现代农业联合研究生院学生"
      };
      return statusMap[row.identity_status] || "未知";
    }
  },
  {
    label: "角色",
    prop: "role_names",
    minWidth: 150,
    align: "center",
    slot: "role"
  },
  {
    label: "IP地址",
    prop: "allow_ip",
    minWidth: 120,
    align: "center",
    slot: "ip"
  },
  {
    label: "状态(禁用/启用)",
    prop: "status",
    width: 140,
    slot: "status",
    align: "center"
  },
  {
    label: "操作",
    width: 200,
    align: "center",
    fixed: "right",
    cellRenderer: ({ row }) => {
      return h("div", { class: "flex justify-center gap-2" }, [
        h(
          ElButton,
          {
            type: "primary",
            link: true,
            onClick: () => handleEditRole(row)
          },
          {
            default: () => [
              h(
                ElIcon,
                { class: "mr-1" },
                {
                  default: () => h(UserFilled)
                }
              ),
              "编辑角色"
            ]
          }
        ),
        h(
          ElButton,
          {
            type: "warning",
            link: true,
            onClick: () => handleEditIp(row)
          },
          {
            default: () => [
              h(
                ElIcon,
                { class: "mr-1" },
                {
                  default: () => h(Edit)
                }
              ),
              "修改IP"
            ]
          }
        )
      ]);
    }
  }
];

// 获取管理员列表数据
const fetchAdminList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: queryForm.name,
      henau_number: queryForm.henau_number,
      section: queryForm.section,
      phone: queryForm.phone,
      status_id: queryForm.status_id,
      identity_status: queryForm.identity_status
    };

    const res = await getAdminerList(params);
    if (res.status === "success") {
      dataList.value = res.data.records.map(item => ({
        ...item,
        status: typeof item.status === "number" ? item.status : 1
      }));
      pagination.total = res.data.pagination.total;
    }
  } catch (error) {
    console.error("获取管理员列表失败:", error);
    ElMessage.error("获取管理员列表失败");
  } finally {
    loading.value = false;
  }
};

// 角色列表数据
const roleOptions = ref<{ id: number; name: string; description: string }[]>(
  []
);

/**
 * 获取全部角色信息
 */
const fetchAllRoles = async () => {
  try {
    const res = await getAllRoles();
    if (res.status === "success") {
      roleOptions.value = res.data;
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("获取角色列表失败");
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchAdminList();
};

// 查询方法
const handleQuery = () => {
  pagination.currentPage = 1;
  fetchAdminList();
};

// 新增管理员
const handleAdd = () => {
  dialogType.value = "add";
  adminForm.value = {
    id: 0,
    name: "",
    avatar_url: "",
    henau_number: "",
    section: "",
    phone: "",
    identity_status: 0,
    role_names: "",
    role_id: [],
    status: 1,
    allow_ip: ""
  };
  dialogVisible.value = true;
};

// 获取本地存储的用户信息
const userInfo = JSON.parse(localStorage.getItem("user-info") || "{}");

// 修改编辑角色方法
const handleEditRole = (row: AdminUser) => {
  // 判断是否是当前用户
  if (row.henau_number === userInfo.username) {
    ElMessage.warning("不能修改自己的角色信息");
    return;
  }

  dialogType.value = "edit";
  // 将字符串形式的role_names转换为role_id数组
  const roleIds = row.role_names
    .split(",")
    .map(name => {
      const role = roleOptions.value.find(r => r.name === name.trim());
      return role ? role.id : null;
    })
    .filter(id => id !== null);

  adminForm.value = {
    ...row,
    role_id: roleIds
  };
  dialogVisible.value = true;
};

// 修改IP方法
const handleEditIp = (row: AdminUser) => {
  // 判断是否是当前用户
  if (row.henau_number === userInfo.username) {
    ElMessage.warning("不能修改自己的IP限制");
    return;
  }

  ElMessageBox.prompt("请输入IP地址，多个IP用英文逗号分隔", "修改IP", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern:
      /^(\d{1,3}\.){3}\d{1,3}(,(\d{1,3}\.){3}\d{1,3})*$|^0\.0\.0\.0$/,
    inputErrorMessage: "请输入正确的IP地址格式，如：192.168.1.1或0.0.0.0",
    inputValue: row.allow_ip ? JSON.parse(row.allow_ip).join(",") : "0.0.0.0"
  })
    .then(async ({ value }) => {
      try {
        const res = await setAllow({
          id: row.id,
          number: parseInt(row.henau_number),
          name: row.name,
          allow_ip: value.split(",").map(ip => ip.trim()),
          default_roles: row.role_id
        });
        if (res.status === "success") {
          ElMessage.success("修改成功");
          fetchAdminList();
        } else {
          ElMessage.error(res.message || "修改失败");
        }
      } catch (error) {
        console.error("修改失败:", error);
        ElMessage.error("修改失败");
      }
    })
    .catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          // TODO: 调用新增接口
        } else {
          // 更新管理员角色
          await setAdminerRole(adminForm.value.id, adminForm.value.role_id);
        }
        ElMessage.success(dialogType.value === "add" ? "新增成功" : "编辑成功");
        dialogVisible.value = false;
        fetchAdminList();
      } catch (error) {
        ElMessage.error(
          error?.response?.data?.msg ||
            (dialogType.value === "add" ? "新增失败" : "编辑失败")
        );
      }
    }
  });
};

const onSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchAdminList();
};

const onCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchAdminList();
};

// 修改处理状态变更的方法
const handleStatusChange = async (row: AdminUser) => {
  const newStatus = row.status; // 获取切换后的新状态
  try {
    await setAdminerStatus(row.id, newStatus);
    ElMessage.success(`${newStatus === 1 ? "启用" : "禁用"}成功`);
    fetchAdminList(); // 刷新列表
  } catch (error) {
    // 如果失败，回滚状态
    row.status = newStatus === 1 ? 0 : 1;
    ElMessage.error(`${newStatus === 1 ? "启用" : "禁用"}失败`);
  }
};

// 添加角色颜色映射缓存
const roleColorMap = new Map<
  string,
  "primary" | "success" | "warning" | "danger" | "info"
>();
const types: ("primary" | "success" | "warning" | "danger" | "info")[] = [
  "primary",
  "success",
  "warning",
  "danger",
  "info"
];

// 修改标签类型函数，根据角色名称返回固定的类型
const getTagType = (
  roleName: string
): "primary" | "success" | "warning" | "danger" | "info" => {
  // 如果已经有颜色映射，直接返回
  if (roleColorMap.has(roleName)) {
    return roleColorMap.get(roleName)!;
  }

  // 如果没有，创建新的映射
  const newType = types[roleColorMap.size % types.length];
  roleColorMap.set(roleName, newType);
  return newType;
};

// 添加角色排序函数
const sortRolesByAdminId = (roleNames: string, roleIds: string) => {
  const roles = roleNames.split(",");
  const ids = roleIds.split(",").map(id => parseInt(id));

  // 将角色名称和ID组合成对象数组
  const roleArray = roles.map((role, index) => ({
    name: role.trim(),
    id: ids[index]
  }));

  // 根据ID排序
  roleArray.sort((a, b) => a.id - b.id);

  // 返回排序后的角色名称数组
  return roleArray.map(role => role.name);
};

// 添加IP标签类型判断函数
const getIpTagType = (
  ip: string
): "success" | "warning" | "danger" | "info" => {
  if (ip === "0.0.0.0") {
    return "warning"; // 允许所有IP访问
  } else if (
    ip.startsWith("192.168.") ||
    ip.startsWith("10.") ||
    ip.startsWith("172.")
  ) {
    return "success"; // 内网IP
  } else if (ip === "127.0.0.1") {
    return "info"; // 本地IP
  } else {
    return "danger"; // 外网IP
  }
};

// 下载模板
const handleDownloadTemplate = () => {
  try {
    // 定义表头
    const headers = ["学工号", "限制IP登录", "姓名", "默认角色组"];

    // 创建示例数据
    const exampleData = [["2890322345", "0.0.0.0", "张三", "默认"]];

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([headers, ...exampleData]);

    // 设置列宽
    const colWidth = headers.map(() => ({ wch: 20 }));
    ws["!cols"] = colWidth;

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "管理员模板");

    // 生成文件并下载
    XLSX.writeFile(wb, "管理员导入模板.xlsx");
  } catch (error) {
    console.error("生成模板失败:", error);
    ElMessage.error("生成模板失败，请稍后重试");
  }
};

// 打开导入对话框
const handleImport = () => {
  fetchAllRoles(); // 获取最新的角色列表
  importDialogVisible.value = true;
};

// 处理文件上传
const handleFileUpload = async file => {
  try {
    // 验证文件类型
    const fileType = file.name.split(".").pop().toLowerCase();
    if (!["xlsx", "xls"].includes(fileType)) {
      ElMessage.error("只能上传 Excel 文件（.xlsx 或 .xls 格式）");
      return false;
    }

    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      ElMessage.error("文件大小不能超过 10MB");
      return false;
    }

    const reader = new FileReader();
    reader.onload = async e => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];

      // 修改这里：使用原始的表头名称
      const jsonData = XLSX.utils.sheet_to_json(worksheet);

      // 验证数据
      const errors = [];
      const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
      const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;

      // 确保已获取最新的角色列表
      await fetchAllRoles();

      jsonData.forEach((row, index) => {
        const rowNum = index + 2;

        // 检查必填字段
        if (!row["学工号"]) errors.push(`第${rowNum}行：学工号不能为空`);
        if (!row["姓名"]) errors.push(`第${rowNum}行：姓名不能为空`);
        if (!row["限制IP登录"])
          errors.push(`第${rowNum}行：限制IP登录不能为空`);
        if (!row["默认角色组"])
          errors.push(`第${rowNum}行：默认角色组不能为空`);

        // 验证IP地址格式
        if (row["限制IP登录"]) {
          const ips = String(row["限制IP登录"])
            .split(",")
            .map(ip => ip.trim());
          ips.forEach(ip => {
            if (
              ip !== "0.0.0.0" &&
              !ipv4Regex.test(ip) &&
              !ipv6Regex.test(ip)
            ) {
              errors.push(
                `第${rowNum}行：IP地址 ${ip} 格式不正确，必须是有效的IPv4或IPv6地址`
              );
            }
          });
        }

        // 验证角色组
        if (row["默认角色组"]) {
          const roleNames = String(row["默认角色组"]).split(",");
          roleNames.forEach(roleName => {
            const trimmedRoleName = roleName.trim();
            const roleExists = roleOptions.value.some(
              role => role.name === trimmedRoleName
            );
            if (!roleExists) {
              errors.push(
                `第${rowNum}行：角色组 ${trimmedRoleName} 在系统中不存在`
              );
            }
          });
        }
      });

      // 如果有错误，显示错误信息并终止导入
      if (errors.length > 0) {
        ElMessage.error({
          message: h("div", {}, [
            h(
              "div",
              { style: "font-weight: bold; margin-bottom: 10px" },
              "导入失败，请检查以下错误："
            ),
            h(
              "div",
              { style: "max-height: 300px; overflow-y: auto" },
              errors.map(error => h("div", { style: "margin: 5px 0" }, error))
            )
          ]),
          duration: 10000
        });
        return false;
      }

      // 处理数据
      const processedData = {
        list: jsonData.map(row => {
          // 处理角色
          const roleNames = String(row["默认角色组"]).split(",");
          const roleIds = roleNames
            .map(name => {
              const role = roleOptions.value.find(r => r.name === name.trim());
              return role ? role.id : null;
            })
            .filter(id => id !== null);

          return {
            number: row["学工号"],
            name: row["姓名"],
            allow_ip: String(row["限制IP登录"])
              .split(",")
              .map(ip => ip.trim()),
            default_roles: roleIds
          };
        })
      };

      // 调用导入接口
      try {
        const res = await preAllow(processedData);
        if (res.status === "success") {
          ElMessage.success("导入成功");
          importDialogVisible.value = false;
          fetchAdminList();
        } else {
          ElMessage.error(res.message || "导入失败");
        }
      } catch (error) {
        console.error("导入失败:", error);
        ElMessage.error("导入失败，请检查数据格式是否正确");
      }
    };
    reader.readAsArrayBuffer(file.raw);
    return false;
  } catch (error) {
    console.error("文件处理失败:", error);
    ElMessage.error("文件处理失败，请检查文件格式");
    return false;
  }
};

// 新增管理员对话框
const addAdminForm = ref({
  number: "",
  name: "",
  allow_ip: "",
  default_roles: []
});

const addAdminRules = {
  number: [{ required: true, message: "请输入学工号", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  allow_ip: [
    { required: true, message: "请输入允许的IP地址", trigger: "blur" }
  ],
  default_roles: [
    { required: true, message: "请选择默认角色", trigger: "change" }
  ]
};

const handleAddAdmin = () => {
  addAdminDialogVisible.value = true;
};

const handleAddAdminSubmit = async () => {
  const formEl = addAdminFormRef.value;
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        const payload = {
          list: [
            {
              number: addAdminForm.value.number,
              name: addAdminForm.value.name,
              allow_ip: [addAdminForm.value.allow_ip],
              default_roles: addAdminForm.value.default_roles
            }
          ]
        };

        const res = await preAllow(payload);
        if (res.status === "success") {
          ElMessage.success("新增管理员成功");
          addAdminDialogVisible.value = false;
          handleQuery(); // 刷新列表
        } else {
          ElMessage.error(res.message || "新增失败");
        }
      } catch (error) {
        ElMessage.error(error?.response?.data?.msg || "新增失败");
      }
    }
  });
};

// 在 script 部分添加以下代码
const filteredRoleOptions = ref([...roleOptions.value]);

// 角色筛选方法
const filterRoles = (query: string) => {
  if (query) {
    filteredRoleOptions.value = roleOptions.value.filter(
      role =>
        role.name.toLowerCase().includes(query.toLowerCase()) ||
        (role.description &&
          role.description.toLowerCase().includes(query.toLowerCase()))
    );
  } else {
    filteredRoleOptions.value = [...roleOptions.value];
  }
};

// 处理下拉框显示/隐藏
const handleRoleSelectVisible = (visible: boolean) => {
  if (visible) {
    filteredRoleOptions.value = [...roleOptions.value];
  }
};

onMounted(() => {
  fetchAdminList();
  fetchAllRoles(); // 获取角色列表
});
</script>

<style lang="scss" scoped>
.adminer-container {
  padding: 20px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  :deep(.el-table) {
    margin-top: 16px;
  }

  .mb-4 {
    margin-bottom: 1rem;
  }

  .mr-2 {
    margin-right: 0.5rem;
  }
}

:deep(.el-table) {
  // 表格基础样式
  .cell {
    padding: 8px 0;
    line-height: 1.5;
  }

  // 表头样式
  .el-table__header {
    th {
      height: 50px;
      font-weight: bold;
      color: var(--el-text-color-primary);
      background-color: var(--el-fill-color-light);
    }
  }
}

.role-tag {
  display: inline-flex;
  align-items: center;
  margin: 2px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
    transform: translateY(-1px);
  }
}
</style>
